<?php
namespace control;

/*
*配料单类
*/
class ingredientsOrderClass extends adIndexClass
{
    private const title = '配料单';
    private const page = 'ingredientsOrder';
    private const table_demand = 'ingredients_demands';//配料需求
    private const table = 'ingredients_order';//配料单
    private const tableMx = 'ingredients_order_detail';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'doneSearch':
                $tr = [
                    'recordDate'          => [
                        'name'  => "配料时间",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => '配料单号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'startDate'         => [
                        'name'  => '开始生产时间',
                        'width' => 200,
                    ],
                    'orderType'          => [
                        'name'  => '单据类型',
                        'width' => 200,
                    ],
                    'machiningOrder'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                    ],
                    'line'          => [
                        'name'  => '生产线',
                        'width' => 200,
                    ],
                    'subject'          => [
                        'name'  => '存货类别',
                        'width' => 200,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '物料名称',
                        'width' => 200,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 200,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 200,
                    ],
                    'num'          => [
                        'name'  => '配料数量',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'style'          => [
                        'name'  => '供料方式',
                        'width' => 200,
                    ],
                    'warehouse'          => [
                        'name'  => '发料仓库',
                        'width' => 200,
                    ]
                ];
                break;
            case 'orderSearch':
                $tr = [
                    'recordDate'          => [
                        'name'  => "配料时间",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => '配料单号',
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'line'         => [
                        'name'  => '生产线',
                        'width' => 300,
                    ],
                    'warehouse'          => [
                        'name'  => '发料仓库',
                        'width' => 300,
                    ],
                    'stid'          => [
                        'name'  => '制单人',
                        'width' => 300,
                    ]
                ];
                break;
            default:
                $tr = [
                    'startDate'          => [
                        'name'  => "开始生产时间",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => '生产订单编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'line'         => [
                        'name'  => '生产线',
                        'width' => 200,
                    ],
                    'subject'          => [
                        'name'  => '存货类别',
                        'width' => 200,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '物料名称',
                        'width' => 200,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 200,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 200,
                    ],
                    'num'          => [
                        'name'  => 'BOM用量',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'sendNum'          => [
                        'name'  => '累计已配数量',
                        'width' => 200,
                    ],
                    'residue'          => [
                        'name'  => '待配数量',
                        'width' => 200,
                    ],
                    'style'          => [
                        'name'  => '供料方式',
                        'width' => 200,
                    ],
                    'warehouse'          => [
                        'name'  => '发料仓库',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $where = self::getWarehouseSql();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "状态" => checkbox(array('name'=>'isClear','value'=>['未清','已清'],'checked'=>['未清'])),
                ],
                [
                    "开始生产日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "生产订单编号"   => text(array("name" => "orderNo")),
                    '生产线' => selectMultiple(["name" => "lineId", 'table' => "product_line",'field'=>"concat(workshop,'-',name) as name,id", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' order by time", 'sqlField' => 'name']),
                ],
                [
                    "物料编码"   => text(array("name" => "code")),
                    "物料名称"   => text(array("name" => "materialName")),
                    "规格型号"   => text(array("name" => "model")),
                ],
                [
                    "仓库" => selectMultiple(["name" => "warehouseId", 'table' => "warehouse", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' $where order by time", 'sqlField' => 'name']),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"commitOrder()\" class='spanButton'>制单</span>\n";
            $button .= "<span class='spanButton' onclick=\"layer('".self::page."','mark','listForm')\">标记为已清</span>".
                componentClass::tipComponent('已配数量>=BOM用量可标记为已清');//采购数量是否已经满足了销售单数量要求
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            'c.name'=>$this->post('materialName'),
            'c.model'=>$this->post('model'),
            'c.code'=>$this->post('code'),
            'b.orderNo'=>$this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'a.coid' => self::$coid,
            'a.lineId'=>$this->post('lineId'),
            'a.warehouseId'=>$this->post('warehouseId')
        );
        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "b.startDate");
        }
        if ($this->post('isClear')) {
            $isClear = [];
            if (in_array('已清',$this->post('isClear'))){
                $isClear[] = 1;
            }
            if (in_array('未清',$this->post('isClear'))){
                $isClear[] = 0;
            }
            //单据日期
            $and.=" and isClear in ('".implode("','",$isClear)."')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,b.orderNo desc,a.list',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table_demand." as a join machining_order as b on a.machiningOrderId = b.id join material as c on a.materialId = c.id" ,
            'field'=>"a.*,c.subject,b.orderNo,b.startDate,c.name as materialName,c.code,c.model",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            $sendNum= find(array('table'=>'ingredients_order_detail','where'=>"coid = '".self::$coid."' and sourceId = '$array[id]'",'sum'=>'num'));
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $line = query('product_line',"id = '$array[lineId]'");
                        $row[] =  $line['workshop'].'-'.$line['name'];
                        break;
                    case 'warehouse':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case 'sendNum':
                        $row[] = self::lostZero($sendNum,'numPrecision');
                        break;
                    case 'residue':
                        $row[] = $array['num']-$sendNum;
                        break;
                    case 'style':
                        $row[] = '配料';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table_demand." as a join machining_order as b on a.machiningOrderId = b.id join material as c on a.materialId = c.id",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num",
        ]);
        $send = find([
            'table'  => 'ingredients_order_detail',
            'single' => " coid = '".self::$coid."' and sourceId in (select a.id from ".self::table_demand." as a join machining_order as b on a.machiningOrderId = b.id join material as c on a.materialId = c.id where 1=1 {$where}) ",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'sendNum'        => self::lostZero($send['num'], 'numPrecision'),
            'residue'        => self::formattingFigure($totalQuery['num'] - $send['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>". $this->js().$page['button'] . clear;
        return json_encode($json, 320);
    }
    public function mark(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否标记所选数据为已清？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "提示", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }
    public function markEdit(): bool|string
    {
        $listId = $this->post('listId');
        if (static::is_null_array($listId)){
            $json['warn'] = '请选择数据';
        }else{
            $x = 0;
            $text = '';
            foreach ($listId as $id){
                $demands = query(self::table_demand,"id = '$id'");
                $machining_order = query('machining_order',"id = '$demands[machiningOrderId]'");
                $warn = update(array('table'=>self::table_demand,'field'=>['isClear'=>1],'where'=>"id = '$id'"));
                $material = query('material',"id = '$demands[materialId]'");
                if ($warn =='更新成功'){
                    $x++;
                    $text.="{$machining_order['type']}单【{$machining_order['orderNo']}】,物料【{$material['code']}-{$material['name']}-{$material['model']}】标记为已清<br>";
                }else{
                    $text.="{$machining_order['type']}单【{$machining_order['orderNo']}】,物料【{$material['code']}-{$material['name']}-{$material['model']}】标记已清失败<br>";
                }
            }
            $text=$this->control['name'].'标记了配料需求如下：'.$text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
            $_SESSION['warn'] = "成功标记了{$x}条数据";
        }
        return json_encode($json,320);
    }

    /**
     * JS
     */
    private function js(){
        $cla = self::page;
        return <<<eof
<script>
function commitOrder(){
     cxDialog('是否确认生成配料单?', () => {
         $.post(root+'control/adIndex.html?cla=$cla&fun=isSameline',$("[name='listForm']").serialize(),function(res) {
              if (res.warn ==2){
                  let arr = [];
                $("[name='listForm'] input[type=checkbox]:checked").each(function () {
                    if ($(this).val() && $(this).val() !== 'on') {
                        arr.push($(this).val());
                    }
                });
                if (arr.length ===0){
                    msg('请选择数据','error')
                    return false;
                }
                let listId = arr.join(",");
                newIframe('生产制造',root+'control/adIndex.html?cla=ingredientsOrder&fun=edit&source=ingredients_demands&module=未配料&lineId='+res.lineId+'&listId='+listId,'生产制造','配料单')
              }else{
                 msg(res.warn,'error')
              }
         },'json')
                
        }, () => {
          // click no callback
        });
}
</script>
eof;

    }

    /**
     * 判断勾选的数据是否是同一个生产线下的
     * @return bool|string
     */
    public function isSameline(): bool|string
    {
        $listId = $this->post('listId');
        if (static::is_null_array($listId)){
            $json['warn'] = '请选择配料数据';
        }else{
            $preSupplierId='';
            foreach ($listId as $id){
                $ingredients_demands = query('ingredients_demands',"id = '$id'");
                if ($ingredients_demands['lineId'] && $preSupplierId && $ingredients_demands['lineId'] !=$preSupplierId){
                    $json['warn'] = "请选择生产线相同的数据";
                    break;
                }
                $preSupplierId  = $ingredients_demands['lineId'];
            }
            if (!isset($json['warn']) || empty($json['warn'])){
                $json['warn'] = 2;
                $json['lineId'] = $preSupplierId;
            }
        }
        return json_encode($json,320);
    }
    /**
     * 获取仓库列表
     * @return string
     */
    public function warehouseList(): string
    {
        //仓库
        $result = find(array('table' => 'warehouse', 'where' => "coid = '" . self::$coid . "' and state = '启用' order by time asc"));
        $li = '';
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $li .= "<li data-id='$array[id]'>{$array['name']}</li>";
            }
        }
        if (empty($li)) {
            $li = "<li>未找到仓库</li>";
        }
        return <<<eof
<div class='warehouse'>仓库&emsp;<span class='del-row-button' id='chooseWareHouse'>批量</span><div class='stateBlock'><ul>{$li}</ul></div></div>
<style>
.stateBlock{margin-top: 0}
.stateBlock ul li{padding: 2px 10px}
</style>
<script>
$("#chooseWareHouse").on('click',function() {
   $(".stateBlock").show();
})
$(".warehouse .stateBlock li").on('click',function() {
    let id = $(this).data('id');
    $("select[name='warehouseId[]']").val(id);
   $(".stateBlock").hide();
})
 //点击非下拉区域隐藏
$(document).bind('click', function (e) {
    let target = $(".stateBlock");
    let obj = $(".warehouse");
    if(!target.is(e.target) && target.has(e.target).length ===0 && !obj.is(e.target) && obj.has(e.target).length ===0){
      target.hide();
    }
});
</script>
eof;
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id');
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];

        $tr[] = ['', '单据编号','单据类型','存货类别', '物料编码', '物料名称','规格型号','单位','待配料数量', $this->warehouseList(),'当前可用库存','配料数量','备注'];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        $totalArr = ['not_num'=>0,'inventory_num'=>0,'total_num'=>0];
        foreach ($result['array'] as $k=>$array) {
            $ingredients_demands = query('ingredients_demands',"id = '$array[sourceId]'");
            $machiningOrder  =query('machining_order',"id = '$ingredients_demands[machiningOrderId]'");
            $material =query('material',"id = '$array[materialId]'");
            $sendNum= find(array(
                'table'=>'ingredients_order_detail',
                'where'=>"coid = '".self::$coid."' and sourceId = '$array[sourceId]' and id !='$array[id]'",
                'sum'=>'num'
            ));
            $inventoryNum = machiningOrderClass::inventory($array['materialId'], $array['unit'], $array['warehouseId']);
            $totalArr['not_num'] += $ingredients_demands['num']-$sendNum;
            $totalArr['inventory_num'] += $inventoryNum;
            $totalArr['total_num'] += $ingredients_demands['num']-$sendNum;
            $tr[] = [
                componentClass::tablePperation($k+1),
                $machiningOrder['orderNo'].
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])).
                hidden(array('name' => 'materialId[]', 'value' => $material['id'])).
                hidden(array('name' => 'sourceId[]', 'value' => $array['sourceId'])),
                machiningInOrderClass::orderType($machiningOrder['orderType']),
                $material['subject'],
                $material['code'],
                $material['name'],
                $material['model'],
                $array['unit'].hidden(array('name'=>'unit[]','value'=>$ingredients_demands['unit'])),
                $array['num']-$sendNum,
                select(array(
                    'name' => 'warehouseId[]',
                    'option' => saleSendOrderClass::warehouseOption($material['id'], $ingredients_demands['unit']),
                    'value' => $array['warehouseId'],
                    'change' => 'getInventory',
                    'title' => '仓库'
                )),
                "<span class='inventory'>$inventoryNum</span>",
                text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision')." onblur=\"calculateTotal()\" ", 'value' => self::lostZero($array['num'],'numPrecision'))),
                text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['text'])),
            ];
        }

        if ($this->get('source') == 'ingredients_demands'){
            $listIdArr = explode(',', $this->get('listId'));
            foreach ($listIdArr as $k=>$sourceId) {
                $mxId = suiji();
                $ingredients_demands = query('ingredients_demands',"id = '$sourceId'");
                $machiningOrder  =query('machining_order',"id = '$ingredients_demands[machiningOrderId]'");
                $material =query('material',"id = '$ingredients_demands[materialId]'");
                $sendNum= find(array('table'=>'ingredients_order_detail','where'=>"coid = '".self::$coid."' and sourceId = '$sourceId'",'sum'=>'num'));
                $inventoryNum = machiningOrderClass::inventory($ingredients_demands['materialId'], $ingredients_demands['unit'], $ingredients_demands['warehouseId']);

                $totalArr['not_num'] += $ingredients_demands['num']-$sendNum;
                $totalArr['inventory_num'] += $inventoryNum;
                $totalArr['total_num'] += $ingredients_demands['num']-$sendNum;
                $inventoryNum = self::lostZero($inventoryNum,'numPrecision');
                $tr[] = [
                    componentClass::tablePperation($k+1),
                    $machiningOrder['orderNo'].
                    hidden(array('name' => 'mxId[]', 'value' => $mxId)).
                    hidden(array('name' => 'materialId[]', 'value' => $material['id'])).
                    hidden(array('name' => 'sourceId[]', 'value' => $ingredients_demands['id'])),
                    machiningInOrderClass::orderType($machiningOrder['orderType']),
                    $material['subject'] ,
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $ingredients_demands['unit'].hidden(array('name'=>'unit[]','value'=>$ingredients_demands['unit'])),
                    self::lostZero($ingredients_demands['num']-$sendNum,'numPrecision'),
                    select(array(
                        'name' => 'warehouseId[]',
                        'option' => saleSendOrderClass::warehouseOption($material['id'], $ingredients_demands['unit']),
                        'value' => $ingredients_demands['warehouseId'],
                        'change' => 'getInventory',
                        'title' => '仓库'
                    )),
                    "<span class='inventory'>$inventoryNum</span>",
                    text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision')." onblur=\"calculateTotal()\" ", 'value' =>  self::formattingFigure($ingredients_demands['num']-$sendNum,'numPrecision'))),
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice')),
                ];
            }
        }

        $lineId = $info['lineId']?:$this->get('lineId');
        $line = query('product_line',"id = '".$lineId."'");
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "生产线：" => $line['workshop'].'-'.$line['name'].hidden(array('name'=>'lineId','value'=>$lineId)),
                    must . "单据日期：" => text(["name" => "recordDate", 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                ],
            ]
        ]);
        $total      = [
            8  => "<span id='not_num'>" . self::lostZero($totalArr['not_num'],'num') . "</span>",
            //10  => "<span id='inventory_num'>" . self::lostZero($totalArr['inventory_num'],'num') . "</span>",
            11  => "<span id='total_num'>" . self::lostZero($totalArr['total_num'],'num') . "</span>",
        ];
        $body .= $this->editList([
            'title' => '配料明细',
            'html' => $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total)),
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        //返回
        $data['html'].=$this->editJs();
        $data['onion'] = ['自制生产', '材料控制', '配料', $this->get('module'),$this->get('module').'详情'];
        return $this->tab($data);
    }


    public function editJs(): string
    {
        return <<<eof
<script>
//获取当前可用库存
function getInventory(e){
    let obj = $(e).parent().parent();
    let warehouseId = e.value;
    let materialId = obj.find("[name='materialId[]']").val();
    let unit = obj.find("[name='unit[]']").val();
    if (!warehouseId){
        msg('请选择仓库');
        obj.find(".inventory").html('');
    }else if(!materialId){
         msg('未找到物料');
        obj.find(".inventory").html('');
    }else if(!unit){
         msg('请选择单位');
        obj.find(".inventory").html('');
    }else{
        $.post(root+'control/adIndex.html?cla=pickOrder&fun=getInventory',{warehouseId:warehouseId,materialId:materialId,unit},function(res) {
              obj.find(".inventory").html(res.num);
              calculateTotal()
        },'json');
    }
}
//计算计划数量
function calculateTotal(table=''){
    table = table ? table : $('.editList')
    let num = 0,
    inventory = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var inventoryText = table.find(".inventory").eq(index).text()
        if(inventoryText){
            inventory+=Number(inventoryText);
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
    $("#inventory_num").text(inventory.toFixed(publicSettings.numPrecision.num));
}
</script>
eof;

    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function editEdit(): bool|string
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $sourceIdArr = $this->post('sourceId');
        $warehouseIdArr = $this->post('warehouseId');
        $numArr = $this->post('num');
        $mxTextArr = $this->post('mxText');
        $field = [
            'lineId' => $this->post('lineId'),
            'recordDate' => $this->post('recordDate'),
        ];
        $annotation = [
            'lineId' => '生产线',
            'recordDate' => '单据日期',
        ];
        $rules = [
            'lineId' => 'required',
            'recordDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power('ingredientsOrderDone', "edit") && !$this->power('ingredientsOrderList', "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr) || static::is_null_array($sourceIdArr)) {
            $json['warn'] = '未找到配料明细';
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = '请填写配料数量';
        }elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此配料单已确认，不能修改';
        } else {
            $this->startTrans();
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'SCPL' . date('Ymd',strtotime($field['recordDate'])),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '".self::$coid."'",
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'state' => '草稿',
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }

            //添加或更新明细
            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::tableMx, "id = '$nid'");
                $ingredients_demands = query('ingredients_demands',"id = '$sourceIdArr[$k]'");
                $numArr[$k] = self::formattingFigure($numArr[$k],'numPrecision');
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableMx,
                        "field" => [
                            'materialId' => $ingredients_demands['materialId'],
                            'num' => $numArr[$k],
                            'unit' => $ingredients_demands['unit'],
                            'sourceId' => $sourceIdArr[$k],
                            'warehouseId'=>$warehouseIdArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                        "where" => " id = '$nid'",
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableMx,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'coid' => self::$coid,
                            'materialId' => $ingredients_demands['materialId'],
                            'num' => $numArr[$k],
                            'unit' => $ingredients_demands['unit'],
                            'sourceTable' => 'ingredients_demands',
                            'sourceId' => $sourceIdArr[$k],
                            'warehouseId'=>$warehouseIdArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                if ($json['warn'] == '新增成功') {
                    auditClass::operateRecord($id,'配料单','新建');
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {

            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if (($this->power('ingredientsOrderDone', "edit") || $this->power('ingredientsOrderList', "edit")) && $info['state'] == '待确认') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "提交",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'commit', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($info['state'] != '已确认') {
                if ($this->power('ingredientsOrderDone', "edit") || $this->power('ingredientsOrderList', "edit")) {
                    //按钮
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => "编辑用户",
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&module={$this->get('module')}&id=" . $info['id'],

                    ];
                }
                if ($this->power('ingredientsOrderList', "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }

            }

            //按钮
//            $button[] = [
//                "name" => "打印",
//                "type" => "点击事件",
//                "fun" => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$info['id']}')",
//            ];

            if (($this->power('ingredientsOrderDone', "cancel") || $this->power('ingredientsOrderList', "cancel")) && $info['state'] == '已确认') {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            $button[] = [
                "name" => "单据追踪",
                "type" => "顶部页卡",
                "title" => "单据追踪",
                "url" => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=配料单&id=" . $info['id'],
            ];
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $tr[] = ['单据编号','单据类型','存货类别', '物料编码', '物料名称','规格型号','单位','待配料数量', '仓库','当前可用库存','配料数量','备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            $totalArr = ['not_num'=>0,'inventory_num'=>0,'num'=>0];
            foreach ($result['array'] as $array) {

                $ingredients_demands = query('ingredients_demands',"id = '$array[sourceId]'");
                $machiningOrder  =query('machining_order',"id = '$ingredients_demands[machiningOrderId]'");
                $material =query('material',"id = '$array[materialId]'");
                $sendNum= find(array(
                    'table'=>'ingredients_order_detail',
                    'where'=>"coid = '".self::$coid."' and sourceId = '$array[sourceId]' and id !='$array[id]'",
                    'sum'=>'num'
                ));
                $inventoryNum = machiningOrderClass::inventory($array['materialId'], $array['unit'], $array['warehouseId']);
                $warehouse = query('warehouse',"id = '$array[warehouseId]'");
                $tr[] = [
                    $machiningOrder['orderNo'],
                    machiningInOrderClass::orderType($machiningOrder['orderType']),
                    $material['subject'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    $array['num']-$sendNum,
                    $warehouse['name'],
                    $inventoryNum,
                    self::lostZero($array['num'],'numPrecision'),
                    $array['text'],
                ];
                $totalArr['not_num'] += $array['num']-$sendNum;
                $totalArr['inventory_num'] += $inventoryNum;
                $totalArr['num'] += $array['num'];
            }
            $line = query('product_line', "id = '$info[lineId]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "生产线" => $line['workshop'] . '-' . $line['name'],
                        "单据日期" => $info['recordDate'],
                        "单据编号" => $info['orderNo'],
                        "制单人" => self::findStaff($info['stid']),
                    ),
                    array(
                        "状态" => $info['state']
                    ),
                ),
            ));
            $total_tr = [
                7 => self::lostZero($totalArr['not_num'], 'num'),
                //9 => self::lostZero($totalArr['inventory_num'], 'num'),
                10 => self::lostZero($totalArr['num'], 'num'),
            ];
            $data['html'] .= $this->detailList([
                'title' => '配料明细',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'showSort' => true, 'total' => $total_tr)),
            ]);
            //生成页面
            $data['onion'] = ['自制生产', '材料控制', '配料', $this->get('module'),$this->get('module').'详情'];
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /*列表页-查询条件*/
    public function doneOptions($isAsync = true)
    {
        $where = self::getWarehouseSql();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "配料时间" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "配料单号"   => text(array("name" => "orderNo")),
                    '生产线' => selectMultiple(["name" => "lineId", 'table' => "product_line",'field'=>"concat(workshop,'-',name) as name,id", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' order by time", 'sqlField' => 'name']),
                ],
                [
                    "物料编码"   => text(array("name" => "code")),
                    "物料名称"   => text(array("name" => "materialName")),
                    "规格型号"   => text(array("name" => "model")),
                ],
                [
                    "仓库" => selectMultiple(["name" => "warehouseId", 'table' => "warehouse", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' $where order by time", 'sqlField' => 'name']),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 已配料
     *
     */
    public function done(): bool|string
    {
        $html = $this->doneOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 已配料
     * @return bool|string
     */
    public function doneSearch(): bool|string
    {
        //like查询数组
        $like = array(
            'c.name'=>$this->post('materialName'),
            'c.model'=>$this->post('model'),
            'c.code'=>$this->post('code'),
            'b.orderNo'=>$this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'a.coid' => self::$coid,
            'b.lineId'=>$this->post('lineId'),
            'a.warehouseId'=>$this->post('warehouseId')
        );
        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "b.recordDate");
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,b.orderNo desc,a.list',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as c on a.materialId = c.id" ,
            'field'=>"a.*,c.subject,b.orderNo,b.lineId,b.recordDate,b.state,c.name as materialName,c.code,c.model",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("doneForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            $ingredients_demands = query('ingredients_demands',"id = '$array[sourceId]'");
            $machiningOrder  =query('machining_order',"id = '$ingredients_demands[machiningOrderId]'");
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&module=已配料&id=" . $array['orderId'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&module=已配料&id=" . $array['orderId'] . "')"),
            );
            if ($array['state'] =='已确认'){
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $line = query('product_line',"id = '$array[lineId]'");
                        $row[] = $line['workshop'].'-'.$line['name'];
                        break;
                    case 'startDate':
                        $row[] = $machiningOrder['startDate'];
                        break;
                    case 'orderType':
                        $row[] = machiningInOrderClass::orderType($machiningOrder['orderType']);
                        break;
                    case 'machiningOrder':
                        $row[] = $machiningOrder['orderNo'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case 'style':
                        $row[] = '配料';
                        break;
                    case 'warehouse':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join material as c on a.materialId = c.id",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='doneForm'>" . $li . "</form>". $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function orderOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "配料时间" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "配料单号"   => text(array("name" => "orderNo")),
                    '生产线' => selectMultiple(["name" => "lineId", 'table' => "product_line",'field'=>"concat(workshop,'-',name) as name,id", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' order by time", 'sqlField' => 'name']),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 已配料
     *
     */
    public function order(): bool|string
    {
        $html = $this->orderOptions(false);
        //控件
        $button = "";
        if ($this->power('ingredientsOrderList', "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /**
     * 已配料
     * @return bool|string
     */
    public function orderSearch(): bool|string
    {
        //like查询数组
        $like = array(
            'orderNo'=>$this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
            'lineId'=>$this->post('lineId'),
        );
        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "recordDate");
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,orderNo',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table,"where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("doneForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&module=配料单&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&module=配料单&id=" . $array['id'] . "')"),
                'track'=> array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=配料单&id=" . $array['id'] . "')"),
            );
            if ($array['state'] =='已确认'){
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $line = query('product_line',"id = '$array[lineId]'");
                        $row[] = $line['workshop'].'-'.$line['name'];
                        break;
                    case 'warehouse':
                        $warehouse = find(array('table'=>'warehouse','field'=>"group_concat(name) as name",'single'=>"id in (select distinct warehouseId from ".self::tableMx." where orderId = '$array[id]')"));
                        $row[] = $warehouse['name'];
                        break;
                    case 'stid':
                        $row[] = self::findStaff($array['stid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='doneForm'>" . $li . "</form>". $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 计算库存占用量
     * @param string $id  领料单ID
     * @param $warehouseId
     * @param $materialId
     * @param $unit
     * @return float
     */
    private function occupy($id, $warehouseId, $materialId, $unit): float
    {
        //未完全出库及未出库的领料总数量
        $pickOrderMx = find(array(
            'table' => self::tableMx." as a join ".self::table." as b on a.orderId = b.id join inventory as c on c.sourceId = b.id",
            'where' => "b.state = '已确认'  and a.warehouseId = '$warehouseId' and a.coid = '" . self::$coid . "' and a.materialId = '$materialId' and c.state !='已出库' and b.id !='$id'", 'field' => "a.num,a.unit"
        ));
        //每一个领料单明细单位都可能不同，所以需要统一为主单位再看需求是否需要转为其他单位
        $pickNum = 0;
        foreach ($pickOrderMx['array'] as $array) {
            $pickNum += machiningOrderClass::material_num_change($materialId, $array['unit'], $unit, $array['num']);
        }
        //出库单中已出库的数量
        $outNum = 0;
        $inventoryMxAll = find(array(
            'table' => 'inventory_detail as a join inventory as b on a.orderId = b.id', 'field' => "a.num,a.unit",
            'where' => "b.state in ('待出库','部分出库')  and b.warehouseId = '$warehouseId' and a.coid = '" . self::$coid . "' and a.materialId = '$materialId' and b.classify=0 and b.sourceTable = '" . self::table . "'"
        ));
        foreach ($inventoryMxAll['array'] as $array) {
            $outNum += machiningOrderClass::material_num_change($materialId, $array['unit'], $unit, $array['num']);
        }
        return self::formattingFigure($pickNum-$outNum, 'numPrecision');
    }

    /**
     * 判断是否超过库存
     * @param $id
     * @return string
     */
    public function moreInventory($id): string
    {
        $warn = '';
        //库存可用量控制
        $inventorySetting = optionSettingClass::getSetting('库存');
        if(isset($inventorySetting['inventoryCtrl']['option']) && $inventorySetting['inventoryCtrl']['option'] && in_array('inventoryOrder',(array)$inventorySetting['inventoryCtrl']['val'])) {
            //判断库存是否足够
            $result = find(array('table' => self::tableMx, "where" => "orderId = '$id' order by list asc"));
            $tempResult = [];
            //判断库存是否可领料,首先需要相同物料分组，避免只判断一个物料够不够
            foreach ($result['array'] as $array) {
                $tempResult[$array['materialId']][$array['warehouseId']][] = [
                    'id' => $array['id'],
                    'unit' => $array['unit'],
                    'num' => $array['num'],
                ];
            }
            foreach ($tempResult as $materialId => $array) {
                foreach ($array as $warehouseId => $childRes) {
                    $material = query('material', "id = '$materialId'","name,unit");
                    //当前可用库存
                    $inventoryNum = machiningOrderClass::inventory($materialId, $material['unit'], $warehouseId);
                    $num = 0;
                    foreach ($childRes as $val) {
                        //占用库存
                        $num += machiningOrderClass::material_num_change($materialId, $val['unit'], $material['unit'], $val['num']);
                    }
                    if ($num > $inventoryNum) {
                        $warn = "物料【{$material['name']}】配料数量已超出可用库存数量";
                        break 2;
                    }
                }
            }
        }
        return $warn;
    }
    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        //判断库存是否足够
        $warn = $this->moreInventory($id);

        if (!$this->power('ingredientsOrderDone', "edit") && !$this->power('ingredientsOrderList', "edit")) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此配料单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此配料单不是草稿状态，不能提交';
        } elseif($warn){
            $json['warn'] = $warn;
        }else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditClass::operateRecord($info['id'],'配料单','提交');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => ''
        ];
        if (!$this->power('ingredientsOrderDone', "cancel") && !$this->power('ingredientsOrderList', "cancel")) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此'.self::title;
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此发'.self::title.'不是已确认状态，无需撤回';
        } elseif (static::total(array('table' => 'inventory', "where" => "sourceId = '$info[id]' and coid = '" . self::$coid . "' and state in ('部分出库','已出库')")) > 0) {
            $json['warn'] = '此'.self::title.'已存在有出库的单据，不能撤回';
        }  else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //删除出库单
                delete(array('table' => 'inventory_detail', 'where' => "orderId in (select id from inventory where sourceId = '$info[id]' and coid = '" . self::$coid . "')"));
                delete(array('table' => 'inventory', 'where' => "sourceId = '$info[id]'"));
                auditClass::operateRecord($id,self::title,'撤回');
                //更新配料需求满足是否已清条件  （累计已配大于等于BOM数量）
                $all = find(array('table'=>self::tableMx,'where'=>"orderId = '$info[id]' order by list asc"));
                foreach ($all['array'] as $array){
                    $ingredients_demands  =query('ingredients_demands',"id = '$array[sourceId]'");
                    $total = find(array('table'=>self::tableMx." as a join ".self::table.' as b on a.orderId = b.id','single'=>"b.state = '已确认' and a.sourceId = '$array[sourceId]'",'field'=>"ifnull(sum(a.num),0) as num"))['num'];
                    if ($total <$ingredients_demands['num']){
                        update(array('table'=>self::table_demand,'field'=>['isClear'=>0],'where'=>"id = '$ingredients_demands[id]'"));
                    }
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        //判断库存是否足够
        $warn = $this->moreInventory($id);
        if (!$this->power('ingredientsOrderDone', "confirm") && !$this->power('ingredientsOrderList', "confirm")) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此' . self::title;
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此' . self::title . '不是待确认状态，不能确认';
        }  elseif($warn){
            $json['warn'] = $warn;
        }else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            //生成出库单
            $bool = $this->insertInventory($info['id']);
            if ($bool !==true){
                $json['warn'] = $bool;
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                auditClass::operateRecord($info['id'],'配料单','确认');

                //更新配料需求满足是否已清条件  （累计已配大于等于BOM数量）
                $all = find(array('table'=>self::tableMx,'where'=>"orderId = '$info[id]' order by list asc"));
                foreach ($all['array'] as $array){
                    $ingredients_demands  =query('ingredients_demands',"id = '$array[sourceId]'");
                    $total = find(array('table'=>self::tableMx." as a join ".self::table.' as b on a.orderId = b.id','single'=>"b.state = '已确认' and a.sourceId = '$array[sourceId]'",'field'=>"ifnull(sum(a.num),0) as num"))['num'];
                    if ($total >=$ingredients_demands['num']){
                        update(array('table'=>self::table_demand,'field'=>['isClear'=>1],'where'=>"id = '$ingredients_demands[id]'"));
                    }
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '确认成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 生成出库单
     * @param $id
     * @return bool|string
     */
    private function insertInventory($id): bool|string
    {
        $info = query(self::table,"id = '$id'");

        $re_array = [];//根据仓库重新分组
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
        foreach ($result['array'] as $array) {
            $re_array[$array['warehouseId']][] = $array['id'];
        }
        $index=1;
        foreach ($re_array as $warehouseId => $array) {
            $id = self::getId();
            $userNo = codeTemplateClass::generateCode('outStockOther',[
                'prefix' => 'KCCK' . date('Ymd'),
                'table' => 'inventory',
                'field' => 'orderNo',
                'where' => " and coid = '".self::$coid."'",
                'index'=>$index
            ],[]);
            $index++;
            $warn = static::insert(array(
                'table' => 'inventory',
                'field' => [
                    'id' => $id,
                    'type' => '配料出库',
                    'coid' => self::$coid,
                    'sourceTable' => self::table,
                    'sourceId' => $info['id'],
                    'warehouseId' => $warehouseId,
                    'targetId' => $info['lineId'],
                    'classify' => 0,
                    'orderNo' => $userNo,
                    'state' => '待出库',
                    'workFlow' => '已质检',
                    'stid' => self::$stid,
                    'orderDate'=>$this->date,
                    'sourceDate'=>$info['recordDate'],
                    'sourceNo'=>$info['orderNo'],
                    'sourceTargetName'=>''
                ]
            ));
            if ($warn != '新增成功') {
                return "新增出库单失败";
            }
            foreach ($array as $mxId) {
                $mx = query(self::tableMx, "id = '$mxId'");
                $price = inventoryDefaultClass::pricingRules('outStockPrice',$mx['materialId'],$mx['unit']);
                $warn = static::insert(array(
                    'table' => 'inventory_detail',
                    'field' => [
                        'id' => self::getId(),
                        'coid' => self::$coid,
                        'sourceTable' => self::tableMx,
                        'sourceId' => $mx['id'],
                        'materialId' => $mx['materialId'],
                        'unit' => $mx['unit'],
                        'warehouseId' => $warehouseId,
                        'orderId' => $id,
                        'orderNum' => $mx['num'],
                        'price' => $price,
                    ]
                ));
                if ($warn != '新增成功') {
                    return "新增出库单明细失败";
                }
            }
        }
        return true;
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此' . self::title . '，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此' . self::title . '？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, doneForm';
                $power = 'ingredientsOrderList';
                break;
        }
        if (!$this->power($power, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power('ingredientsOrderList', "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => 'ingredientsOrderList', "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
